<?php

namespace App\Applet\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Match;
use App\Models\MatchReport;
use App\Models\Stage;
use App\Models\User;

class MatchController extends Controller
{
    // 获取报名选手
	public function reportUsersList(Request $request)
    {
    	$m = Match::selectNormal()->find($request->match_id);
        $r = MatchReport::selectNormal()
        	->with(['user' => function ($q) {
	        	$q->selectNormal();
	        }])->where('match_id', $request->match_id)->get();
        // foreach ($r as &$v) {
        //     $v->user->name = substr($v->user->name, 0, 6);
        // }
        return $this->success(['match' => $m, 'report' => $r]);
    }

    // 获取一个比赛中我的小比赛
    public function getMyStage(Request $request)
    {
        $user = $this->getAuthenticatedUser();
        if (!$user) {
            return $this->error('亲，请先登录');
        }
        $mids = MatchReport::where('user_id', $user->id)->pluck('match_id')->toArray();
        $stage = Stage::with('match')->whereIn('match_id', $mids)->get()->toArray();
        $data = [];
        foreach ($stage as &$stagev) {
            if (in_array($user->id, $stagev['result']['user_ids'])) {
                $sort = rand(0, count($stagev['result']['user_ids']) - 1);
                foreach ($stagev['result']['user_ids'] as $k => $uid) {
                    if ($k == $sort) {
                        Stage::setWinFail($stagev, $uid, 'win');
                    } else {
                        Stage::setWinFail($stagev, $uid, 'fail');
                    }
                }
                if ($stagev['result']['win']['id'] == $user->id) {
                    $stagev['result']['left'] = $stagev['result']['win'];
                    $stagev['result']['right'] = $stagev['result']['fail'];
                    $stagev['result']['left']['is_win_fail'] = 'win';
                    $stagev['result']['right']['is_win_fail'] = 'fail';
                    $stagev['result']['win_fail_img_left'] = 'https://alicdn.joyballet.cn/match_manager/mine_left_win.png';
                    $stagev['result']['win_fail_img_right'] = 'https://alicdn.joyballet.cn/match_manager/mine_right_fail.png';
                } else {
                    $stagev['result']['left'] = $stagev['result']['fail'];
                    $stagev['result']['right'] = $stagev['result']['win'];
                    $stagev['result']['left']['is_win_fail'] = 'fail';
                    $stagev['result']['right']['is_win_fail'] = 'win';
                    $stagev['result']['win_fail_img_left'] = 'https://alicdn.joyballet.cn/match_manager/mine_left_fail.png';
                    $stagev['result']['win_fail_img_right'] = 'https://alicdn.joyballet.cn/match_manager/mine_right_win.png';
                }
                $stagev['date'] = date('Y-m-d', strtotime($stagev['match']['begin_time']));
                $data[] = [
                    'data' => $stagev
                ];
            }
        }
        $user = User::selectNormal()->with(['level', 'group'])->find($user->id);
        return $this->success([
            'user' => $user,
            'stage' => $data
        ]);
    }

    // 根据报名人员生成小比赛
    public function makeStage(Request $request)
    {
        $match = Match::with('reportPeople')->find($request->match_id);
        if (!$match) {
            return $this->error('比赛不存在');
        }
        $stage = Stage::where('match_id', $match->id)->get()->toArray();
        // 根据参赛人数生成小比赛
        $uids = [];
        foreach ($match->reportPeople as $rv) {
            $uids[] = $rv['user_id'];
        }
        $_uids = $uids;
        $data = [];
        foreach ($uids as $uid) {
            foreach ($_uids as $_uid) {
                $data[] = [
                    'u1' => $uid,
                    'u2' => $_uid,
                    'uids' => [$uid, $_uid],
                ];
            }
            $key = array_search($uid, $_uids); 
            if ($key !== false) {
                unset($_uids[$key]);
            }           
        }
        // 查看是否已经生成过小比赛了
        $sql = [];
        foreach ($data as $v) {
            $is_exist = false;
            foreach ($stage as $stagev) {
                if (isset($stagev['result']['user_ids'])
                 && empty(array_diff($v['uids'], $stagev['result']['user_ids']))) {

                    $is_exist = true;
                }
            }
            if (!$is_exist) {
                $sql[] = [
                    'name' => $match->name,
                    'match_id' => $match->id,
                    'result' => [
                        'user_ids' => $v['uids'],
                    ],
                ];
            }
        }
        Stage::insert($sql);
        return $this->success('小比赛更新成功');
    }
}